package com.alex.springbootdemo.service.impl;


import com.alex.springbootdemo.common.Constants;
import com.alex.springbootdemo.common.ResultCode;
import com.alex.springbootdemo.enums.SettingKeysEnum;
import com.alex.springbootdemo.mapper.mbg.SystemSettingsMapper;
import com.alex.springbootdemo.model.pojo.SystemSettings;
import com.alex.springbootdemo.service.SystemSettingService;
import com.alex.springbootdemo.utils.AssertUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.weekend.Weekend;

import java.util.Date;

@Service
@AllArgsConstructor
@Slf4j
@CacheConfig(cacheNames = Constants.CACHE_SYSTEM_SETTING)
public class SystemSettingServiceImpl implements SystemSettingService {

    private final SystemSettingsMapper systemSettingsMapper;

    @Override
    @Cacheable(unless = "#result == null", key = "#key.name()")
    public SystemSettings getByKey(SettingKeysEnum key) {
        Weekend<SystemSettings> weekend = Weekend.of(SystemSettings.class);
        weekend.weekendCriteria()
                .andEqualTo(SystemSettings::getSettingKey, key.name());
        SystemSettings systemSettings = systemSettingsMapper.selectOneByExample(weekend);
        AssertUtil.isNotNull(systemSettings, ResultCode.ASSERT_ERROR, "未找到对应SystemSetting系统配置");
        return systemSettings;
    }


    @Override
    public void addSetting(SystemSettings systemSettings) {
            systemSettings.setCreateDate(new Date());
            systemSettingsMapper.insertSelective(systemSettings);
    }

    @Override
    @CachePut(key = "#systemSettings.settingKey")
    public SystemSettings saveSetting(SystemSettings systemSettings) {
        AssertUtil.isNotNull(systemSettings.getId(),"id不能为空");
        SystemSettings dbSystemSettings = systemSettingsMapper.selectByPrimaryKey(systemSettings.getId());
        AssertUtil.isNotNull(dbSystemSettings,"未找到对应系统配置信息");
        dbSystemSettings.setSettingKey(systemSettings.getSettingKey())
                .setSettingValue(systemSettings.getSettingValue())
                .setUpdateDate(new Date());
        systemSettingsMapper.updateByPrimaryKeySelective(dbSystemSettings);
        return dbSystemSettings;
    }


}
